<script setup lang="ts">
import { orderStatusMap, OrderStatus } from '@/pagesOrder/api/constants.ts'
import { getOrderListApi } from '@/pagesOrder/api/order.ts'
import type { ListOrderItem, ListOrderParams } from '@/types/order'
import { onUnmounted, ref } from 'vue'
import { confirmReceiptApi, delOrderApi, payMockApi } from '@/pagesOrder/api/order.ts'
import debounce from 'lodash.debounce'
import { unFinished } from '@/utils/unFinished.ts'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getWindowInfo()

// 获取 props 参数
const props = defineProps<{
  activeStatus: OrderStatus
}>()

// 请求参数
const queryParams: ListOrderParams = {
  page: 1,
  pageSize: 5,
  orderState: props.activeStatus,
}
// 订单总数量
const orderPages = ref(0)
// 获取订单列表
const orderList = ref<ListOrderItem[]>([])
// 存储请求控制器
let abortRequest: () => void
const getOrderList = async () => {
  const { promise, abort } = getOrderListApi(queryParams)
  // 存储请求控制器，用于取消请求
  abortRequest = abort
  // 等待结果
  const res = await promise
  // 每次请求都会添加新数据
  orderList.value.push(...res.result.items)
  orderPages.value = res.result.pages
}
getOrderList()

// 支付订单
const payOrder = debounce(async (id: string) => {
  await payMockApi({ orderId: id })

  uni.showToast({ title: '支付成功' })
  const curOrder = orderList.value?.find((item) => item.id === id)
  curOrder!.orderState = OrderStatus.DaiFaHuo
}, 500)

// 确认收货
const confirmReceipt = async (id: string) => {
  // 二次确认弹窗
  uni.showModal({
    content: '为保障您的权益，请收到货并确认无误后，再确认收货',
    success: async (success) => {
      if (success.confirm) {
        await confirmReceiptApi(id)

        uni.showToast({ title: '收货成功' })
        const curOrder = orderList.value?.find((item) => item.id === id)
        curOrder!.orderState = OrderStatus.DaiPingJia
      }
    },
  })
}

// 删除订单
const delOrder = async (id: string) => {
  // 二次确认弹窗
  uni.showModal({
    content: '确定要删除该订单吗？',
    success: async (success) => {
      if (success.confirm) {
        await delOrderApi({ ids: [id] })

        uni.showToast({ title: '删除成功' })
        orderList.value = orderList.value?.filter((item) => item.id !== id)
      }
    },
  })
}

// 同一时间仅允许发送一个上拉加载请求
const isLoading = ref(false) // 🔐 锁变量
const finish = ref(false)
// 滚动触底加载更多
const onScrolltolower = async () => {
  if (isLoading.value) return // 1️⃣ 检查锁状态
  isLoading.value = true // 2️⃣ 加锁
  try {
    // 3️⃣ 分页控制：当前页 >= 总页数时停止加载
    if (queryParams.page! >= orderPages.value) {
      finish.value = true
      return uni.showToast({ icon: 'none', title: '没有更多数据~' })
    }
    // 请求下一页数据
    queryParams.page!++
    await getOrderList() // 4️⃣ 异步操作
  } finally {
    isLoading.value = false // 5️⃣ 释放锁（确保异常时也能解锁）
  }
}

// 组件销毁时取消请求
onUnmounted(() => {
  abortRequest()
})
</script>

<template>
  <!-- 订单列表，后端有个bug，后端没有正确修改倒计时结束的商品状态为已取消 -->
  <scroll-view scroll-y class="orders" @scrolltolower="onScrolltolower">
    <view class="card" v-for="order in orderList" :key="order.id">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ order.createTime }}</text>
        <!-- 订单状态文字 -->
        <text>{{ orderStatusMap[order.orderState].text }}</text>
        <!-- 待评价/已完成/已取消 状态: 展示删除订单 -->
        <text
          class="icon-delete"
          v-if="
            [OrderStatus.DaiPingJia, OrderStatus.YiWanCheng, OrderStatus.YiQuXiao].includes(
              order.orderState,
            )
          "
          @tap="delOrder(order.id)"
        ></text>
      </view>
      <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
      <navigator
        v-for="sku in order.skus"
        :key="sku.id"
        :url="`/pagesOrder/pages/detail/detail?id=${order.id}`"
        hover-class="none"
      >
        <view class="goods">
          <view class="cover">
            <!-- #ifdef MP-WEIXIN -->
            <image mode="aspectFit" :src="sku.image" lazy-load></image>
            <!-- #endif -->
            <!-- #ifdef APP-PLUS || H5 -->
            <img :src="sku.image" loading="lazy" alt="" />
            <!-- #endif -->
          </view>
          <view class="meta">
            <view class="name ellipsis">{{ sku.name }}</view>
            <view class="type">{{ sku.attrsText }}</view>
          </view>
        </view>
      </navigator>
      <!-- 支付信息 -->
      <view class="payment">
        <text class="quantity">共{{ order.totalNum }}件商品</text>
        <text>实付</text>
        <text class="amount">
          <text class="symbol">¥</text>
          {{ order.payMoney }}
        </text>
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 -->
        <template v-if="order.orderState === OrderStatus.DaiFuKuan">
          <view class="button primary" @tap="payOrder(order.id)">去支付</view>
        </template>
        <template v-else>
          <!-- 待发货/待收货/待评价/已完成状态: 展示申请售后 -->
          <view
            v-if="
              [
                OrderStatus.DaiFaHuo,
                OrderStatus.DaiShouHuo,
                OrderStatus.DaiPingJia,
                OrderStatus.YiWanCheng,
              ].includes(order.orderState)
            "
            class="button secondary"
            @tap="unFinished"
          >
            申请售后
          </view>
          <navigator
            class="button secondary"
            :url="`/pagesOrder/pages/create/create?orderId=${order.id}`"
            hover-class="none"
          >
            再次购买
          </navigator>
          <!-- 待收货状态: 展示确认收货 -->
          <view
            v-if="order.orderState === OrderStatus.DaiShouHuo"
            class="button primary"
            @tap="confirmReceipt(order.id)"
            >确认收货
          </view>
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view
      class="loading-text"
      :style="{ paddingBottom: safeAreaInsets.bottom ? safeAreaInsets.bottom + 'px' : '20rpx' }"
    >
      {{ finish ? '没有更多数据~' : '正在加载...' }}
    </view>
  </scroll-view>
</template>

<style lang="scss">
// 订单列表
.orders {
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
